package com.kk.xhr.model.service.impl;

import com.kk.xhr.common.pojo.CandidateStatusEnum;
import com.kk.xhr.model.assembler.CandidateStructKit;
import com.kk.xhr.model.dao.CandidateDynamicSqlSupport;
import com.kk.xhr.model.dao.CandidateMapper;
import com.kk.xhr.model.dto.CandidateDTO;
import com.kk.xhr.model.dto.CandidateQueryRequestDTO;
import com.kk.xhr.model.dto.PageDto;
import com.kk.xhr.model.entity.Candidate;
import com.kk.xhr.model.service.ICandidateService;
import lombok.RequiredArgsConstructor;
import org.mybatis.dynamic.sql.where.AbstractWhereDSL;
import org.springframework.stereotype.Repository;

import java.util.Optional;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualToWhenPresent;

/**
 * 候选人服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/4/6
 * @since 1.0.0
 */
@Repository
@RequiredArgsConstructor
public class CandidateServiceImpl implements ICandidateService {
    private final CandidateMapper candidateMapper;
    private final CandidateStructKit instance = CandidateStructKit.INSTANCE;

    @Override
    public PageDto<CandidateDTO> queryPage(CandidateQueryRequestDTO dto) {
        long count = candidateMapper.count(dsl -> applyQueryArgs(dsl.where(), dto));
        if (0 == count) {
            return PageDto.empty();
        }
        return new PageDto<>(count, candidateMapper.select(dsl -> applyQueryArgs(dsl.where(), dto)
            .orderBy(CandidateDynamicSqlSupport.id.descending())
            .limit(dto.getLimit())
            .offset(dto.getOffset()))
            .stream()
            .map(instance::toDto)
            .collect(Collectors.toList()));
    }

    @Override
    public Optional<CandidateDTO> query(Long id) {
        return candidateMapper.selectByPrimaryKey(id).map(instance::toDto);
    }

    @Override
    public void add(CandidateDTO dto) {
        candidateMapper.insertSelective(instance.toEntity(dto));
    }

    @Override
    public void modify(CandidateDTO dto) {
        candidateMapper.updateByPrimaryKeySelective(instance.toEntity(dto));
    }

    @Override
    public void modifyStatus(Long id, CandidateStatusEnum status) {
        if (null == status) {
            return;
        }
        candidateMapper.updateByPrimaryKeySelective(new Candidate().withId(id).withStatus(status.getValue()));
    }

    private <T extends AbstractWhereDSL<T>> T applyQueryArgs(T where, CandidateQueryRequestDTO dto) {
        where.and(CandidateDynamicSqlSupport.recruitId, isEqualToWhenPresent(dto.getRecruitId()));
        if (null != dto.getStatus()) {
            where.and(CandidateDynamicSqlSupport.status, isEqualTo(dto.getStatus().getValue()));
        }
        return where;
    }
}
